import {App} from "obsidian";
import Mustache from 'mustache';
import {TemplateSetting} from "./settings";

export class Dispatch {
    // private tagExtractRegex = /#[^\s]+/g;
    private app: App;
    private tagExtractRegex = /(?<!#)#[^#\s]+/g;
    private memo: Record<string, string>;
    private templates: TemplateSetting[]; // #obimport/flag/待办提醒 -> xxxxxx

    // private memoContent: string;
    // private allTags: string[] = [];
    // private dispatchToCardTag: string; // Tag: Card Filename
    // private dispatchToHeadingTag: string; // Tag: Heading
    // private todoTags: string[] = [];
    // private generalTags: string[] = [];

    private result: DispatchInfo = new DispatchInfo();

    constructor(app: App, memo: Record<string, string>, templates: TemplateSetting[]) {
        this.app = app;
        this.templates = templates;
        // for (const item of templates){
        //     this.templates.set(item.name, item.template);
        // }
        // this.result.bullet = true;
        this.result.multipleLine = false;
        // this.result.todoStatus = ToDoStatus.None;

        this.memo = memo;
        const allTags = memo.content.match(this.tagExtractRegex);
        this.result.memoContent = memo.content;
        for (const item of this.templates){
            if (item.name.trim() === "default"){ // templateName=待办提醒/XXX, item.name=待办提醒
                this.result.template = item.template;
                break;
            }
        }
        if (allTags) {
            for (const tag of allTags) {
                if (tag.startsWith("#inline") || tag.startsWith("#left") || tag.startsWith("#right") || tag.startsWith("#center")){ // 图片嵌入的hash标签需要排除
                    continue;
                }
                if (tag.startsWith("#obimport/heading")) {
                    this.result.type = DispatchType.Heading;
                    this.result.filename = this.memo.date;
                    this.result.heading = tag.split("/").slice(-1)[0];
                } else if (tag.startsWith("#obimport/card")) {
                    this.result.type = DispatchType.Card;
                    const lines = this.result.memoContent.trim().split("\n");
                    if (lines.length > 0) {
                        this.result.filename = `2_Cards/${tag.replace("#obimport/cards/","")}/${lines[0]}.md`;
                    } else {
                        this.result.filename = `2_Cards/${tag}/untitled.md`;
                    }
                } else if (tag.startsWith("#obimport/flag/多行")) {
                    this.result.multipleLine = true;
                }
                else if (tag.startsWith("#obimport/flag/")) {
                    const templateName = tag.replaceAll("#obimport/flag/", "");
                    for (const item of this.templates){
                        if (templateName.startsWith(item.name)){ // templateName=待办提醒/XXX, item.name=待办提醒
                            this.result.template = item.template;
                            break;
                        }
                    }
                }
                // else if (tag.startsWith("#obimport/flag/nobullet")) {
                //     this.result.bullet = false; // 这个可以用Mustache处理模板
                // } else if (tag.startsWith("#obimport/flag/待办提醒")) {
                //     if (tag.startsWith("#obimport/flag/待办提醒/已完成")) {
                //         this.result.todoStatus = ToDoStatus.Done; // 这个可以用Mustache处理模板
                //     } else {
                //         this.result.todoStatus = ToDoStatus.Todo; // 这个可以用Mustache处理模板
                //     }
                // }
                else {
                    this.result.tags.push(tag); // 这里再增加一个default template，默认模板就是有bullets的
                }
                this.result.memoContent = this.result.memoContent.replaceAll(tag, "");
            }
        }
    }

    createTemplateView(): any {
        return {
            content: this.result.memoContent,
            title: this.memo.title,
            date: this.memo.date,
            datetime: this.memo.datetime,
            time: this.memo.time,
        }
    }
    processContentTemplate() {
        // if (!this.template) {
        //     let content = ``;
        //
        //     if (article.content) {
        //         content += article.content + '\n\n';
        //     }
        //
        //     if (article.highlights && article.highlights.length > 0) {
        //         content += '## Highlights\n\n';
        //         article.highlights.forEach(highlight => {
        //             content += `- ${highlight.text}\n`;
        //         });
        //     }
        //
        //     return content;
        // }

        if (this.result.template) {
            // 1. 创建 ArticleView 对象
            const mustacheView = this.createTemplateView();

            // 2. 只有当模板中包含 content_highlighted 字段且文章有内容和高亮时才生成高亮内容
            // if (template.includes('content_highlighted') && article.content && article.highlights && article.highlights.length > 0) {
            //     articleView.content_highlighted = this.generateHighlightedContent(article.content, article.highlights);
            // }

            // 3. 使用 Mustache 渲染模板
            this.result.memoContent = Mustache.render(this.result.template, mustacheView);
        }
    }

    private removeNewline() {
        this.result.memoContent = this.result.memoContent.replaceAll("\n", " ").replaceAll("\r", " ");
    }
    private processMultipleLine() {
        // 处理flagTags
        // if (this.flagTags.includes("#obimport/flag/多行")) {
        if (this.result.multipleLine) {
            // 多行模式处理逻辑
            const lines = [];
            for (let line of this.result.memoContent.trim().split("\n")) {
                if (line.startsWith("\\*")) { // 如果原始memo有"\*"（这个是在flomo读html时遗留的问题），那么替换成标准的bullet
                    line = "*" + line.substring(2, line.length);
                }
                line = `${line} #flo_temp_mo`; // 多行情况下，每一行都要有一个#flo_temp_mo标签
                lines.push(line);
            }
            this.result.memoContent = lines.join("\n");
        } else {
            // 单行模式处理逻辑
            // this.appendBulletPrefix();
            this.removeNewline();
            this.result.memoContent = this.result.memoContent.trim() + " #flo_temp_mo";
            // this.result.tags.push("#flo_temp_mo");
        }
    }

    // private appendTodoPrefix() {
    //     if (this.result.todoStatus == ToDoStatus.Todo) {
    //         this.result.memoContent = "- [ ] " + this.result.memoContent;
    //     } else if (this.result.todoStatus == ToDoStatus.Done) {
    //         this.result.memoContent = "- [x] " + this.result.memoContent;
    //     }
    //     // for (const tag of this.todoTags) {
    //     //     if (tag == "#obimport/flag/待办提醒/待办") {
    //     //         this.result.memoContent = "- [ ] " + this.result.memoContent;
    //     //         break;
    //     //     } else if (tag == "#obimport/flag/待办提醒/已完成") {
    //     //         this.result.memoContent = "- [x] " + this.result.memoContent;
    //     //         break;
    //     //     } else if (tag == "#obimport/flag/待办提醒/意向中") {
    //     //         this.result.memoContent = "- [ ] " + this.result.memoContent;
    //     //         break;
    //     //     } else if (tag == "#obimport/flag/待办提醒") {
    //     //         this.result.memoContent = "- [ ] " + this.result.memoContent;
    //     //         break;
    //     //     }
    //     // }
    // }

    // private appendBulletPrefix() {
    //     if (this.result.heading.endsWith("思考总结")) {
    //         this.result.memoContent = `* ${this.memo.time.split(":").slice(0, 2).join(":")} ` + this.result.memoContent;
    //     } else if (this.result.todoStatus == ToDoStatus.None) {
    //         if (this.result.bullet) {
    //             this.result.memoContent =  "* " + this.result.memoContent;
    //         }
    //     }
    // }

    public async dispatch(): Promise<DispatchInfo>{
        // 这里是真正做dispatch，constructor中都是在处理输入
        // 应该讲importer.cs中的逻辑放在这里
        // const result: DispatchResult = new DispatchResult();
        if (this.result.type == DispatchType.Heading) {
            // result.filename = this.memo.date;
            // result.heading = this.dispatchToHeadingTag.split("/").slice(-1)[0];
            // const prefix = this.getPrefix(result.heading);
            // this.memoContent = prefix + this.memoContent;
            // this.processFlagTag(result.heading);
            // this.appendTodoPrefix();
            this.processMultipleLine();
            this.processContentTemplate();
            // this.appendGeneralTags();
            // result.anchor = "";
        } else if (this.result.type == DispatchType.Card) {
            // const lines = this.memoContent.trim().split("\n");
            // if (lines.length > 0) {
            //     // const folder = this.dispatchToCardTag.split("/").slice(1).join("/");
            //     result.filename = `2_Cards/${this.dispatchToCardTag.replace("#obimport/cards/","")}/${lines[0]}.md`;
            // } else {
            //     result.filename = `2_Cards/${this.dispatchToCardTag}/untitled.md`;
            // }
            // result.heading = null;
            // result.anchor = null;
        }
        // result.memoContent = this.memoContent;
        // result.tags = this.generalTags;

        return this.result;
    }
}

enum DispatchType {
    Heading = "heading",
    Card = "card",
    Undefined = "undefined",
}
// enum ToDoStatus{
//     None = "none",
//     Todo = "todo",
//     Done = "done",
// }
export class DispatchInfo {
    public type: DispatchType;
    public filename: string;
    public heading: string;
    // public bullet: boolean;
    public multipleLine: boolean;
    // public todoStatus: ToDoStatus;
    public template: string;
    public memoContent: string;
    public tags: string[];
    public anchor: string;
    constructor() {
        this.type = DispatchType.Undefined;
        this.filename = "";
        this.heading = "";
        // this.bullet = false;
        this.multipleLine = false;
        // this.todoStatus = ToDoStatus.None;
        this.template = "";
        this.memoContent = "";
        this.tags = [];
        this.anchor = "";
    }
}